﻿@using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs
@using ResizeMode = SixLabors.ImageSharp.Processing.ResizeMode
@using Size = SixLabors.ImageSharp.Size
@using Image = SixLabors.ImageSharp.Image
@using SixLabors.ImageSharp.Processing
@using SixLabors.ImageSharp
@using SixLabors.ImageSharp.Formats.Png
@using CleanArchitecture.Blazor.Application.Features.Identity.DTOs
@using CleanArchitecture.Blazor.Domain.Common.Enums
@using CleanArchitecture.Blazor.Domain.Identity
@using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant
@inherits OwningComponentBase
@inject IValidationService Validator
@inject IUploadService UploadService
@inject ITenantService TenantsService
@inject IStringLocalizer<Users> L

<MudForm Model="@Model" @ref="@_form" Validation="@(Validator.ValidateValue(Model))">
    <input For="@(() => Model.Id)" @bind-value="Model.Id" type="hidden" @bind-value:event="oninput" />
    <input For="@(() => Model.ProfilePictureDataUrl)" @bind-value="Model.ProfilePictureDataUrl" type="hidden" @bind-value:event="oninput"/>

    <MudGrid Spacing="2">
        <MudItem sm="12">
            <div class="d-flex justify-center">

                @if (string.IsNullOrEmpty(Model.ProfilePictureDataUrl))
                {
                    <MudAvatar Style="height:128px; width:128px; font-size:2rem;">@Model.UserName.ToUpper().FirstOrDefault()</MudAvatar>
                }
                else
                {
                    <MudAvatar Style="height:128px; width:128px; font-size:2rem;">
                        <MudImage Src="@Model.ProfilePictureDataUrl"></MudImage>
                    </MudAvatar>
                }
                <MudTooltip Text="@L["Click upload a image"]">
                    <MudFileUpload T="IBrowserFile" Accept=".jpg, .jpeg, .png, .webp" FilesChanged="UploadPhoto" Style="margin-top:-10px;margin-left:-15px">
                        <ActivatorContent>
                            <MudIconButton Icon="@Icons.Material.Filled.PhotoCamera">
                            </MudIconButton>
                        </ActivatorContent>
                    </MudFileUpload>
                </MudTooltip>

            </div>
        </MudItem>
        <MudItem sm="6" xs="12">
            <MultiTenantAutocomplete For="@(() => Model.Tenant)"
                                     T="TenantDto"
                                     Label="@L[Model.GetMemberDescription(x=>x.Tenant)]"
                                     Required="true"
                                     ValueChanged="@(x=>TenantChanged(x))"
                                     Value="@Model.Tenant">

            </MultiTenantAutocomplete>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => Model.Provider)" @bind-Value="Model.Provider" Label="@L[Model.GetMemberDescription(x=>x.Provider)]"  ReadOnly="true"></MudTextField>
        </MudItem>

        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => Model.UserName)" @bind-Value="Model.UserName" Label="@L[Model.GetMemberDescription(x=>x.UserName)]"  Required="true"></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <div class="d-fex">
                <MudCheckBox For="@(() => Model.IsActive)" @bind-Value="Model.IsActive" Label="@L[Model.GetMemberDescription(x=>x.IsActive)]"></MudCheckBox>
            </div>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => Model.DisplayName)" @bind-Value="Model.DisplayName" Label="@L[Model.GetMemberDescription(x=>x.DisplayName)]" ></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <PickSuperiorIdAutocomplete For="@(() => Model.Superior)" T="ApplicationUserDto"
                                        OwnerName="@Model.UserName"
                                        Clearable="true"
                                        TenantId="@Model.Tenant?.Id"
                                        Label="@L[Model.GetMemberDescription(x=>x.Superior)]"
                                        @bind-Value="@Model.Superior">
            </PickSuperiorIdAutocomplete>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => Model.Email)" @bind-Value="Model.Email" Label="@L[Model.GetMemberDescription(x=>x.Email)]"  Required="true"></MudTextField>
        </MudItem>
        <MudItem xs="12" sm="6">
            <MudTextField For="@(() => Model.PhoneNumber)" @bind-Value="Model.PhoneNumber" Label="@L[Model.GetMemberDescription(x=>x.PhoneNumber)]" ></MudTextField>
        </MudItem>
        <MudItem sm="6" xs="12">
            <TimeZoneAutocomplete T="string" For="@(() => Model.TimeZoneId)"  @bind-Value="Model.TimeZoneId" Label="@L[Model.GetMemberDescription(x=>x.TimeZoneId)]" ></TimeZoneAutocomplete>
        </MudItem>
        <MudItem sm="6" xs="12">
            <LanguageAutocomplete T="string" For="@(() => Model.LanguageCode)"  @bind-Value="Model.LanguageCode" Label="@L[Model.GetMemberDescription(x=>x.LanguageCode)]" ></LanguageAutocomplete>
        </MudItem>


        <MudItem xs="12" sm="12">
            <MudText Typo="Typo.body1">@L["Assign Roles"]</MudText>
            <MudGrid Class="mt-1" Spacing="2">
                @if (Roles.Any())
                {
                    @for (var i = 0; i < Roles.Count; i++)
                    {
                        var x = i;
                        <MudItem xs="6" sm="6" Class="py-0 my=0">
                            <MudCheckBox T="bool" Value="@Roles[x].Value" Label="@Roles[x].Key" ValueChanged="@(s => Roles[x].Value = s)"></MudCheckBox>
                        </MudItem>
                    }

                }
                else
                {
                    <MudAlert Class="flex-grow-1" Severity="Severity.Warning">@L["No roles available for this tenant."]</MudAlert>
                }

            </MudGrid>
        </MudItem>
        <MudItem sm="6" xs="12">
            <MudTextField For="@(() => Model.CreatedBy)" Disabled  Value="Model.CreatedByUser?.UserName" Label="@L[Model.GetMemberDescription(x=>x.CreatedBy)]" ></MudTextField>
        </MudItem>
        <MudItem sm="6" xs="12">
            <MudTextField T="string" Disabled  Value="@(Model.Created.ToLocalTime(UserProfile?.LocalTimeOffset))" Label="@L[Model.GetMemberDescription(x=>x.Created)]" ></MudTextField>
        </MudItem>
        <MudItem sm="6" xs="12">
            <MudTextField For="@(() => Model.LastModifiedBy)" Disabled  Value="Model.LastModifiedByUser?.UserName" Label="@L[Model.GetMemberDescription(x=>x.LastModifiedBy)]" ></MudTextField>
        </MudItem>
        <MudItem sm="6" xs="12">
            <MudTextField T="string" Disabled  Value="@(Model.LastModified.ToLocalTime(UserProfile?.LocalTimeOffset))" Label="@L[Model.GetMemberDescription(x=>x.LastModified)]" ></MudTextField>
        </MudItem>
    </MudGrid>
</MudForm>

@code {
    [Parameter]
    public UserProfile? UserProfile { get; set; }
    public class CheckItem
    {
        public string Key { get; set; } = string.Empty;
        public bool Value { get; set; }
    }
    private RoleManager<ApplicationRole> RoleManager = null!;
    [EditorRequired][Parameter] public ApplicationUserDto Model { get; set; } = default!;

    [EditorRequired][Parameter] public EventCallback<ApplicationUserDto> OnFormSubmit { get; set; }


    private MudForm? _form = default!;
    private List<CheckItem> Roles { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        RoleManager = ScopedServices.GetRequiredService<RoleManager<ApplicationRole>>();
        await GetRoles(Model.TenantId);
    }
    private async Task GetRoles(string? tenantId)
    {
        Roles = new();
        var array = await RoleManager.Roles.Where(x => x.TenantId == Model.TenantId).Select(x => x.Name).ToListAsync();
        foreach (var role in array)
        {
            if (Model.AssignedRoles != null && Model.AssignedRoles.Contains(role))
            {
                Roles.Add(new CheckItem { Key = role!, Value = true });
            }
            else
            {
                Roles.Add(new CheckItem { Key = role!, Value = false });
            }
        }
    }
    private async Task TenantChanged(TenantDto? x)
    {
        Model.TenantId = x?.Id;
        Model.Tenant = x;
        await GetRoles(Model.TenantId);
    }
    private async Task UploadPhoto(IBrowserFile file)
    {
        var filestream = file.OpenReadStream(GlobalVariable.MaxAllowedSize);
        var imgStream = new MemoryStream();
        await filestream.CopyToAsync(imgStream);
        imgStream.Position = 0;
        using (var outStream = new MemoryStream())
        {
            using (var image = Image.Load(imgStream))
            {
                image.Mutate(
                    i => i.Resize(new ResizeOptions { Mode = ResizeMode.Crop, Size = new Size(128, 128) }));
                image.Save(outStream, PngFormat.Instance);
                var filename = file.Name;
                var fi = new FileInfo(filename);
                var ext = fi.Extension;
                var result = await UploadService.UploadAsync(new UploadRequest($"{Model.Id}_{DateTime.UtcNow.Ticks}.png", UploadType.ProfilePicture, outStream.ToArray()));
                Model.ProfilePictureDataUrl = result;

                //Do your validations here
                Snackbar.Add(ConstantString.UploadSuccess, Severity.Info);
            }
        }
    }

    public async Task Submit()
    {
        if (_form is not null)
        {
            await _form.Validate();
            if (_form.IsValid)
            {
                Model.AssignedRoles = Roles.Where(x => x.Value).Select(x => x.Key).ToArray();
                await OnFormSubmit.InvokeAsync(Model);
            }
        }
    }

}